package com.edan.partnerback.common;

import com.edan.partnerback.handle.RedisCommentChangeListener;
import com.edan.partnerback.handle.RedisPraiseChangeListener;
import com.edan.partnerback.handle.RedisViewChangeListener;
import com.edan.partnerback.utils.FastJsonRedisSerializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) throws Exception {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
    // 创建基本的key监听器
    /*  */
    @Bean
    public RedisPraiseChangeListener redisPraiseChangeListener(RedisConnectionFactory connectionFactory) throws Exception {
        return new RedisPraiseChangeListener(redisMessageListenerContainer(connectionFactory));
    }
    @Bean
    public RedisViewChangeListener redisViewChangeListener(RedisConnectionFactory connectionFactory) throws Exception {
        return new RedisViewChangeListener(redisMessageListenerContainer(connectionFactory));
    }
    @Bean
    public RedisCommentChangeListener redisCommentChangeListener(RedisConnectionFactory connectionFactory) throws Exception {
        return new RedisCommentChangeListener(redisMessageListenerContainer(connectionFactory));
    }

}
